<template>
  <view class="content">
    <view class="app-title ac">
      <view class="fl" @click="back">
        <image class="back" src="/static/img/back.png"></image>
      </view>
      <text @click="addressTest()">编辑问题单</text>
    </view>
    <view class="top-bg"></view>

    <view class="detail">
      <u-cell-group>
        <u-cell-item
          title="接报时间:"
          :value="
            data_list.receiveTime == '' ? '请选择' : data_list.receiveTime
          "
          @click="
            show_date = true;
            date_type = 'receiveTime';
          "
        >
        </u-cell-item>
        <u-cell-item
          title="问题开始时间:"
          :value="
            data_list.faultStartTime == '' ? '请选择' : data_list.faultStartTime
          "
          @click="
            show_date = true;
            date_type = 'faultStartTime';
          "
        >
        </u-cell-item>
        <u-radio-group
          v-model="data_listFaultstatus"
          style="height: 50px; width: 100%"
          placement="row"
        >
          <text
            style="display: inline-block; line-height: 50px; margin-right: 20%"
            >问题位置:</text
          >
          <u-radio :name="1" :disabled="false">车站</u-radio>
          <u-radio :name="2" :disabled="false">区间</u-radio>
          <u-radio :name="3" :disabled="false">列车</u-radio>
        </u-radio-group>
        <u-cell-item
          title="线路"
          :value="lineName == '' ? '请选择' : lineName"
          @click="
		  label_name = 'name';
		  value_name = 'idK';
            show_picker = true;
            columns = line_options;
          "
        ></u-cell-item>
        <!-- <u-cell-item title="问题地点" :value="stationName == '' ? '请选择' : stationName"
					@click="show_picker=true; columns = station_options"></u-cell-item> -->
        <u-cell-item
          title="问题地点"
          :value="stationName == '' ? '请选择' : stationName"
          @click="show_station = true;  label_name = 'name';
            value_name = 'id';"
        ></u-cell-item>
        <u-cell-item
          title="填  写 人:"
          :value="username"
          :arrow="false"
        ></u-cell-item>
        <u-cell-item title="发  现 人:" :value="data_list.discoverer" @click="show_people = true;
        columns = leaderOptions;
        label_name = 'name';
        selece_type='people'
        value_name = 'idK';">
        
        	</u-cell-item>
        	<u-field v-model="data_list.contactPhone" label="发现人联系电话:" placeholder="请填写"></u-field>
        </u-cell-group>

      <u-radio-group
        v-model="data_listOwnerDepartment"
        style="height: 50px; width: 100%"
        placement="row"
      >
        <text
          style="display: inline-block; line-height: 50px; margin-right: 34%"
          >是否是本部门问题:</text
        >
        <u-radio :name="1" :disabled="false">是</u-radio>
        <u-radio :name="2" :disabled="false">否</u-radio>
      </u-radio-group>
	  <hr/>
	  <u-cell-item title="设备类型:" :value="!data_list.equTypeName ? '请选择' : data_list.equTypeName"
	  	@click="getEquTypeByStationId() ">
	  </u-cell-item>
	  
	  <u-cell-item title="设备:" :value="data_list.equName?data_list.equName:'请选择'"
	  	@click.self="show_device = true;  getEquList();deviceName=data_list.equName">
	  </u-cell-item>
	  <u-cell-item title="问题现象" :value="data_list.faultItem == '' ? '请选择' : data_list.faultItem"
	    @click="checkReson" ></u-cell-item>
    <view class="job-detail"><text>问题现象概述：</text> </view>
    <textarea class="text" v-model="data_list.faultIssue"></textarea>
      <view class="job-detail">备注及其它：</view>
      <textarea class="text" v-model="data_list.remark"></textarea>
      <view class="btn">
        <button style="margin-right: 34rpx" class="cancel-btn fl" @click="back">
          取消
        </button>
        <button class="default-btn" @click="pushData(1)">保存</button>
        <button class="default-btn fr" @click="pushData(2)">提交</button>
      </view>
    </view>

    <view class="full" v-show="show_picker || show_date || show_station"></view>
    <u-picker
      v-model="show_date"
      mode="time"
      :params="params"
      @confirm="setDate"
      @cancel="onCancel"
    ></u-picker>
   <u-select v-model="show_picker" :list="columns" :label-name="label_name" :value-name="value_name"
   	@confirm="onConfirm" @cancel="onCancel">
   </u-select>

    <SelectStation
      v-show="show_station"
      :stationName="stationName"
      :faultStatus="data_listFaultstatus"
      :station="station_options"
      @close="show_station = false"
      @setStation="setStation"
    ></SelectStation>
	<selectDevice v-show="show_device" :deviceName="deviceName" :device="optionEquName" @close="show_device = false"
		@setDevice="setDevice"></selectDevice>
	<PeopleSelect v-if="show_people" :people="leaderOptions" :peopleName="data_list.discoverer"
		@setPeople="setPeople" :faultStatus='1' @close="show_people=false"> </PeopleSelect>
  </view>
</template>

<script>
	import {
		PMS_DICT_CONTROLLER,
		WORK_CONTROLLER
	} from "../../api/pms";
	import {
		EQUCONTROLLER
	} from '../../api/eqt.js'
	import SelectStation from "../../components/faultClosedLoop/selectStation";
	import selectDevice from '../../components/myWork/viewWork/selectDevice.vue'
	import PeopleSelect from "../../components/faultClosedLoop/peopleSelect.vue"
	import {
		mapState
	} from "vuex";
export default {
  components: { 	
	    SelectStation,
	    selectDevice, 
		PeopleSelect},
  watch: {
    data_listFaultstatus(newValue, oldValue) {
      // this.initOptions()
      this.lineName = "";
      this.stationName = "";
      this.station_options = [];
    },
  },
  computed: {
  	...mapState([
  		"workOrderType",
  		"workProfession",
  		"workOrderState",
  		"lineTree",
  		"reeByOrgnum",
  		"userInfo",
		"fault"
  
  	]),
  },
  data() {
    return {
		label_name: "",
		value_name: "",
      // username: this.$store.state.userInfoFaultCL.username,
      username: uni.getStorageSync("username") || "",
      lineName: "",
      line_options: "",
      stationName: "",
      station_options: [],
      params: {
        year: true,
        month: true,
        day: true,
        hour: true,
        minute: true,
        second: true,
      },
      columns: [],
      data_listFaultstatus: "",
      data_listOwnerDepartment: "",
      data_list: {
        contactPhone: "",
        discoverer: "",
        faultIssue: "",
        faultLocation: [""],
        faultStartTime: "",
        faultstatus: "",
        lineId: "",
        faultIssue: "",
        ownerDepartment: "",
        receiveTime: "",
        remark: "",
        subType: "",
	equName: "",
	equId: "",
	equTypeId: "",
	equTypeName: ""
      },
      detailID: "",
	  date_type: true,
	  show_picker: false,
	  show_date: false,
	  show_station: false,
	  show_device: false,
	  show_people: false,
	  deviceName: "",
	  optionEqu: [],
	  optionEquName: [],
	  stationGroup: [],
	  leaderOptions: []
    };
  },
  created() {
	  this.lineTree.map((item) => {
	  	item.extra = {
	  		type: "line",
	  	};
	  });
    this.initDetailData();
    this.initOptions();
    this.username = uni.getStorageSync("username");
    this.setReceiveTime();
	this.getNameByOrgId()
  },
  onBackPress() {
    uni.switchTab({
      url: "/pages/index/index",
    });
  },
  onLoad(options) {
    console.log(options);
    // console.log(this.$mp.page.route);
    this.detailID = options.id;
  },
  methods: {
	  checkReson(){
	  this.columns = this.fault
	  this.selece_type ="reason"
	  this.label_name='value'
	  this.value_name = "code"
	  this.show_picker = true
	  	
	  },
	  setPeople(obj) {
	  	this.data_list.discoverer = obj.name.toString();
	  	// this.listOrderData.constructPerson = obj.id.toString();
	  	let leaderId = obj.id.toString()
	  	let filterPeople = this.leaderOptions.filter(item => item.idK == leaderId)
	  	this.data_list.contactPhone = filterPeople[0]?.phone
	  	this.show_people = false;
	  },
	  getNameByOrgId() {
	  	this.fetch(
	  		"get",
	  		this.$store.state.baseUrl + WORK_CONTROLLER.GET_NAME_BY_ORGID, {
	  			num: ''
	  		}
	  	).then((res) => {
	  		if (res?.success) {
	  			this.leaderOptions = res?.data;
	  		}
	  	});
	  
	  },
	  filterStation() {
	  	if (this.data_listFaultstatus == 1) {
	  		this.stationGroup.forEach(item => {
	  			let type = item.type.split('-')
	  			if (type[1] == '车站') {
	  				this.station_options = item.station
	  			}
	  		})
	  	}
	  	if (this.data_listFaultstatus == 2) {
	  		this.stationGroup.forEach(item => {
	  			let type = item.type.split('-')
	  			if (type[1] == '区间') {
	  				this.station_options = item.station
	  			}
	  		})
	  	}
	  },
	  setDevice(obj) {
	  	this.data_list.equName = obj.name.toString();
	  	this.data_list.equId = obj.id.toString();
	  	this.show_device = false;
	  },
	  getEquTypeByStationId(param) {
	  	if (this.data_list.faultLocation.length == 0){
	  		 uni.showToast({
	  			title: "请先选择问题地点~",
	  			icon: "none",
	  		});
	  		return
	  	}
	  	this.columns = []
	  	this.fetch(
	  		"GET",
	  		this.$store.state.baseUrl + EQUCONTROLLER.GET_EQU_TYPE_BY_STATIONID, {
	  			stationId: this.data_list.faultLocation.toString(),
	  		}, false
	  	).then((res) => {
	  		if (res.returnCode == 2004) {
	  			this.selece_type = 'equTypeName'
	  			this.label_name = 'name'
	  			this.value_name = 'idk'
	  			this.columns = res?.data
	  			console.log('this.columns', this.columns)
	  			this.show_picker = true
	  		}
	  	})
	  },
	  /**
	   * 根据选择的设备类型获取 设备列表 
	   */
	  async getEquList() {
	  	this.fetch(
	  		"post",
	  		this.$store.state.baseUrl + WORK_CONTROLLER.POST_EQU_EQULIST, {
	  			equtype: this.data_list.equTypeId,
	  			stationId: this.data_list.faultLocation.toString(),
	  			page: 1,
	  			size: 9999999,
	  		}, false
	  	).then((res) => {
	  		if (res?.data) {
	  			this.optionEquName = res?.data?.content;
	  			this.optionEquName = this.reduceArray(this.optionEquName, "idk");
	  		}
	  	})
	  },
	  // 数组对象元素去重
	  reduceArray(initialArr, attr) {
	  	// const uniqueArr = Array.from(new Set(arr.map(JSON.stringify)), JSON.parse);
	  	let uniqueArr = initialArr.reduce((acc, obj) => {
	  		let existingObj = acc.find((item) => item[attr] === obj[attr]);
	  		if (!existingObj) {
	  			acc.push(obj);
	  		}
	  		return acc;
	  	}, []);
	  	return uniqueArr;
	  },
	  radioGroupFaultStatusChange(e) {
	  	// console.log(e);
	  },
    initDetailData() {
      this.fetch(
        "GET",
        this.$store.state.baseFaultUrl + "/fault/get/" + this.detailID,{},
        false,
        this.$store.state.faultCLHeader
      ).then((res) => {
        if (res.success) {
          this.data_list = (({
            dealContent,
            message,
            orgIds,
            reason,
            receiveTime,
            lineId,
            faultLocation,
            createName,
            discoverer,
            faultIssue,
            contactPhone,
            faultStartTime,
            faultLevel,
            dutyOrg,
            limitTime,
            faultstatus,
            contingency,
            ownerDepartment,

            misinfor,
            remark,
	    equName,
            equId,
	    equTypeName,
	    equTypeId,
	    faultSymptomList,
		faultItem
          }) => ({
            dealContent,
            message,
            orgIds,
            reason,
            receiveTime,
            lineId,
            faultLocation,
            createName,
            discoverer,
            faultIssue,
            contactPhone,
            faultStartTime,
            faultLevel,
            dutyOrg,
            limitTime,
            faultstatus,
            ownerDepartment,
            contingency,
            misinfor,
            remark,
	    equName,
	    equId,
	    equTypeName,
	    equTypeId,
	    faultSymptomList,
		faultItem
          }))(res.data);

          this.faultSymptomList = res.data.faultSymptomList;
          this.faultSystemList = res.data.faultSystemList;

          this.faultLevelName = res.data.faultLevel ? 	   
                   res.data.faultLevel + "类问题" :	     
		   "";
          this.dutyOrgName = res.data.dutyOrgName;
          this.data_listFaultstatus =
            ["车站", "区间", "列车"].indexOf(this.data_list.faultstatus) + 1 ||
            "";
          this.$nextTick(() => {
            this.getFaultPosAndAssign(res.data.lineId, res.data.faultLocation);
            this.lineName = res.data.lineName;
            this.stationName = res.data.faultLocationName;
          });
          this.data_listOwnerDepartment =
            ["Y", "N"].indexOf(this.data_list.ownerDepartment) + 1 || "";
          this.data_listContingency =
            ["Y", "N"].indexOf(this.data_list.contingency) + 1 || "";
          this.data_listMisinfor =
            ["Y", "N"].indexOf(this.data_list.misinfor) + 1 || "";
        }
      });
    },
    // 获取问题地点并且赋值
    getFaultPosAndAssign(lineId, selArr) {
      if (this.data_listFaultstatus == 3) {
        this.fetch(
          "GET",
          this.$store.state.baseFaultUrl + "/pmsDict/train/getNameByLineId",
          {
            lineId: lineId,
          },
          false,
          this.$store.state.faultCLHeader
        ).then((res) => {
          if (res.success) {
            this.station_options = res.data || []; //暂时特殊处理
            this.station_options.map((item) => {
              let flag = selArr.indexOf(item.id);
              item.extra = {
                type: "station",
                checked: flag != -1 ? true : false,
                id: item.id,
              };
              item.checked = flag != -1 ? true : false;
              item.text = item.name;
            });
          }
        });
        return;
      } else {
        this.fetch(
          "GET",
          this.$store.state.baseFaultUrl + "/kunmingdict/station/nameGroupType",
          {
            lineIds: lineId,
          },
          false,
          this.$store.state.faultCLHeader
        ).then((res) => {
          if (res.success) {
            let temp = [];
            res.data.forEach((item) => {
              temp = temp.concat(item.childs);
            });
            // this.station_options = res.data[0].childs || []; //暂时特殊处理
            temp.map((item) => {
              let flag = selArr.indexOf(item.id);
              item.extra = {
                type: "station",
                checked: flag != -1 ? true : false,
                id: item.id,
              };
              item.checked = flag != -1 ? true : false;
              item.text = item.name;
            });
            console.log(temp);
            this.station_options = temp;
          }
        });
      }
    },
    radioGroupFaultStatusChange(e) {
      console.log(e);
    },
    addressTest() {
      uni.showToast({
        title: this.$store.state.baseFaultUrl,
        icon: "none",
      });
    },
    back() {
      uni.navigateBack();
    },
    setReceiveTime() {
      let now = new Date();
      let str =
        now.getFullYear() +
        "-" +
        (now.getMonth() + 1 < 10
          ? "0" + (now.getMonth() + 1)
          : now.getMonth() + 1) +
        "-" +
        (now.getDate() < 10 ? "0" + now.getDate() : now.getDate()) +
        " " +
        (now.getHours() < 10 ? "0" + now.getHours() : now.getHours()) +
        ":" +
        (now.getMinutes() < 10 ? "0" + now.getMinutes() : now.getMinutes()) +
        ":" +
        (now.getSeconds() < 10 ? "0" + now.getSeconds() : now.getSeconds());
      this.data_list.receiveTime = str;
    },
    onConfirm(item) {
     	if (item[0]?.extra?.type == "line") {
					this.lineName = item[0].label;
					this.data_list.lineId = item[0].value;
					this.stationName = "";
					console.log('this.data_list',this.data_list,item)
					this.getStationOption(this.data_list.lineId);
				} else if (item[0]?.extra?.type == "station") {
					this.stationName = item[0].label;
					this.data_list.faultLocation = [item[0].extra.id];
				} else if (this.selece_type == 'equTypeName') {
					this.data_list.equTypeName = item[0].label
					this.data_list.equTypeId = item[0].value
					this.getEquList()
				} else if (this.selece_type == 'people') {
					this.data_list.discoverer = item[0].label
					let leaderId = item[0].value
					let filterPeople = this.leaderOptions.filter(item => item.idK == leaderId)
					this.data_list.contactPhone = filterPeople[0]?.phone
				} else if(this.selece_type == "reason"){
					this.data_list.faultProblem =item[0].label
					this.data_list.faultItem =  item[0].label
				}

      this.onCancel();
    },
    onCancel() {
      this.show_picker = false;
      this.show_date = false;
      this.show_station = false;
    },
    setDate(obj) {
      let str =
        obj.year +
        "-" +
        obj.month +
        "-" +
        obj.day +
        " " +
        obj.hour +
        ":" +
        obj.minute +
        ":" +
        obj.second;
      switch (this.date_type) {
        case "receiveTime":
          this.data_list.receiveTime = str;
          break;
        case "faultStartTime":
          this.data_list.faultStartTime = str;
          break;
        default:
      }
      this.onCancel();
    },
    initOptions() {
      this.fetch(
        "GET",
        this.$store.state.baseFaultUrl + "/kunmingdict/line/name",
        {
          status: "",
        },
        true,
        this.$store.state.faultCLHeader
      ).then((res) => {
        if (res.success) {
          this.line_options = res.data;
          this.line_options.map((item) => {
            item.extra = {
              type: "line",
              id: item.id,
            };
            item.text = item.name;
          });
        }
      });
    },

			getStationOption() {
				if (this.data_listFaultstatus == 3) {
					this.fetch(
						"GET",
						this.$store.state.baseFaultUrl + "/pmsDict/train/getNameByLineId", {
							lineId: this.data_list.lineId,
						},
						false,
						this.$store.state.faultCLHeader
					).then((res) => {
						if (res.success) {
							this.station_options = res.data || []; //暂时特殊处理
							this.station_options.map((item) => {
								item.extra = {
									type: "station",
									checked: false,
									id: item.id,
								};
								item.text = item.name;
							});
						}
					});
					return;
				} else {
					this.fetch(
						"GET",
						this.$store.state.baseFaultUrl + "/kunmingdict/station/nameGroupType", {
							lineIds: this.data_list.lineId,
						},
						false,
						this.$store.state.faultCLHeader
					).then((res) => {
						if (res.success) {
							console.log('res---', res)
							let temp = [];
							let copyTemp = []
							res.data.forEach((item) => {
								temp = temp.concat(item.childs);
							});
							copyTemp = res.data.map(item => {
								let child = item.childs.map(chilItem => {
									return {
										...chilItem,
										extra: {
											type: "station",
											checked: false,
											id: chilItem.id,
										}
									}
								})
								return {
									type: item.type,
									station: child
								}
							})
							// this.station_options = res.data[0].childs || []; //暂时特殊处理
							temp.map((item) => {
								item.extra = {
									type: "station",
									checked: false,
									id: item.id,
								};
								item.text = item.name;
							});
							this.stationGroup = copyTemp
							this.station_options = temp;
							console.log('this.station_options', this.station_options, copyTemp)
						} else {
							this.station_options = [];
						}
					});
				}
			},
			setStation(obj) {
				this.stationName = obj.name.toString();
				this.data_list.faultLocation = obj.id;
				this.show_station = false;
			},
			pushData(submitType) {
				if (this.checkInputNull() != "success") return;

				this.data_list.faultstatus =
					this.data_listFaultstatus == 1 ?
					"车站" :
					this.data_listFaultstatus == 2 ?
					"区间" :
					"列车";
				this.data_list.ownerDepartment =
					this.data_listOwnerDepartment == 1 ? "Y" : "N";
				this.data_list.subType = submitType;
				this.data_list.id = this.detailID;

				// //暂时特殊处理
				// this.data_list.ownerDepartment = 'Y';
				// if (this.data_list.faultstatus == "区间")
				// this.data_list.faultstatus = "车站";

				if (this.data_list.contactPhone) {
					if (!/^1[3|4|5|7|8]\d{9}$/.test(this.data_list.contactPhone))
						return uni.showToast({
							title: "手机号码有误，请重填",
							icon: "none",
						});
				}
				if (
					new Date(this.data_list.faultStartTime).getTime() >
					new Date(this.data_list.receiveTime).getTime()
				)
					return uni.showToast({
						title: "问题开始时间不能晚于接报时间",
						icon: "none",
					});
				if (
					this.data_list.faultstatus == "区间" &&
					this.data_list.faultLocation.length != 2
				)
					return uni.showToast({
						title: "请选择两个站点~",
						icon: "none",
					});
				this.data_list.faultSymptomParams = this.data_list.faultSymptomList
				this.data_list.faultSymptomParams[0].content = this.data_list.faultIssue
					this.data_list.faultSymptomParams[0].faultProblem = this.data_list.faultProblem
				this.fetch(
					"POST",
					this.$store.state.baseFaultUrl + "/fault/update",
					this.data_list,
					true,
					this.$store.state.faultCLHeader
				).then((res) => {
					if (res.success) {
						uni.showToast({
							title: "操作完成",
							icon: "none",
						});
						setTimeout(() => {
							uni.navigateTo({
								url: "/pages/index/index",
							});
						}, 800);
					} else {
						uni.showToast({
							title: res.message,
							icon: "none",
						});
					}
				});
			},
			checkInputNull() {
				if (this.data_list.receiveTime == "")
					return uni.showToast({
						title: "接报时间不能为空",
						icon: "none",
					});
				if (this.data_list.faultStartTime == "")
					return uni.showToast({
						title: "问题开始时间不能为空",
						icon: "none",
					});
				if (this.data_listFaultstatus == "")
					return uni.showToast({
						title: "问题位置不能为空",
						icon: "none",
					});
				if (this.data_list.lineId == "")
					return uni.showToast({
						title: "线路不能为空",
						icon: "none",
					});
				if (this.data_list.faultLocation[0] == "")
					return uni.showToast({
						title: "问题地点不能为空",
						icon: "none",
					});
				if (this.data_list.discoverer == "")
					return uni.showToast({
						title: "发现人不能为空",
						icon: "none",
					});
				// if (this.data_list.contactPhone == '') return uni.showToast({
				// 	title: '发现人电话不能为空',
				// 	icon: 'none'
				// });

				if (this.data_list.faultIssue == "")
					return uni.showToast({
						title: "问题现象不能为空",
						icon: "none",
					});
				if (this.data_listOwnerDepartment == "")
					return uni.showToast({
						title: "请选择是否为本部门问题",
						icon: "none",
					});
				if (
					this.data_listFaultstatus == 2 &&
					this.data_list.faultLocation.length > 2
				)
					return uni.showToast({
						title: "只能选择两个地点",
						icon: "none",
					});
				return "success";
			},
		},
	};
</script>

<style scoped>
.detail {
  height: auto;
  padding-bottom: 16px;
  margin-top: -170px;
}

.job-detail {
  line-height: 45px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding-right: 20px;
  align-items: center;
}

.detail > .text {
  background: #f9fbfe;
  border: 1px solid #f1f1f1;
  border-radius: 6px;
  padding: 10px;
  font-size: 14px;
  height: 104px;
  overflow: auto;
}

	.detail>.photo {
		overflow-x: auto;
		width: 100%;
		height: 100px;
		white-space: nowrap;
	}

	.detail>.photo>.img-item {
		width: 80px;
		height: 80px;
		margin-right: 10px;
		border-radius: 6px;
		display: inline-block;
		vertical-align: middle;
	}

	.detail>.btn {
		margin: 30rpx 26rpx 0 0;
	}

	.detail>.btn>button {
		display: inline-block;
		width: 30%;
	}

	.photo .images {
		width: 80px;
		height: 80px;
	}

	.van-cell {
		padding: 13px 16px;
	}

	.van-hairline--top-bottom::after,
	.van-hairline-unset--top-bottom::after {
		border-top: 0px;
	}

	.van-cell__value {
		color: #3e3a39;
	}

	hr {
		border: 0;
		border-top: 1px solid #F2F3F6;
	}
</style>